package com.keepers.repair.service;


import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.SystemClock;

import com.keepers.repair.net.LogUtil;

public class CoreService extends Service {

    public static final String CORESERVICE_ALARM = "CORESERVICE_ALARM";

    private static AlarmManager  localAlarmManager;
    private        PendingIntent sender;

    @Override
    public void onCreate() {
        super.onCreate();
        startAlarm();
        LogUtil.e("_SPI_SERVICE _CoreService_ onCreate()");
    }

    @SuppressLint("ShortAlarm")
    public void startAlarm() {
        LogUtil.e("_SPI_SERVICE _CoreService_ startAlarm()-S-Build.VERSION.SDK_INT：" + Build.VERSION.SDK_INT);
        if (localAlarmManager != null) {
            localAlarmManager.cancel(sender);
            localAlarmManager = null;
        }
        localAlarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, NotifyReceiver.class);
        intent.setAction(CORESERVICE_ALARM);
        sender = PendingIntent.getBroadcast(this, 0, intent, 0);
        //开始时间
        long firstime = SystemClock.elapsedRealtime();
        localAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstime, 5000, sender);
        LogUtil.e("_SPI_SERVICE _CoreService_ localAlarmManager.setInexactRepeating()");
        LogUtil.e("_SPI_SERVICE _CoreService_ startAlarm()-E-firstime:" + firstime);
    }

    @Override
    public void onDestroy() {
        // 退出前台服务，同时清掉状态栏通知。
        // 在api 18的版本上，这时候状态栏通知没了，但InnerCoreService还在，且仍旧是前台服务状态，目的达到。
        if (localAlarmManager != null) {
            localAlarmManager.cancel(sender);
            localAlarmManager = null;
        }
        LogUtil.e("_SPI_SERVICE _CoreService_ onDestroy()");
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        LogUtil.e("_SPI_SERVICE _CoreService_ onBind()");
        return null;
    }

    public static void startCoreService(Context context) {
        context = context.getApplicationContext();
        LogUtil.e("_SPI_SERVICE _CoreService_ startCoreService()-S-");
        context.startService(new Intent(context, CoreService.class));
        LogUtil.e("_SPI_SERVICE _CoreService_ startCoreService()-E-");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.e("_SPI_SERVICE " + "_CoreService_ onStartCommand()flags:" + flags + " startId:" + startId);
        return START_STICKY;
    }
}
